package com.gxc.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 自定义 ServletRequestWrapper类.
 *
 * @author 宫新程
 * @since 2019/1/14 1:20 PM
 */
public class MyServletRequestWrapper extends HttpServletRequestWrapper {

  private byte[] buffer;

  /** 获取字节数组. */
  public MyServletRequestWrapper(HttpServletRequest request) throws IOException {
    super(request);
    ServletInputStream inputStream = request.getInputStream();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] bytes = new byte[1024];
    int len;
    while ((len = inputStream.read(bytes)) != -1) {
      outputStream.write(bytes, 0, len);
    }
    this.buffer = outputStream.toByteArray();
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
    return new ServletInputStream() {
      @Override
      public boolean isFinished() {
        return false;
      }

      @Override
      public boolean isReady() {
        return false;
      }

      @Override
      public void setReadListener(ReadListener readListener) {}

      @Override
      public int read() throws IOException {
        return inputStream.read();
      }
    };
  }

  @Override
  public BufferedReader getReader() throws IOException {
    return new BufferedReader(new InputStreamReader(getInputStream()));
  }
}
